﻿using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        [CtxMenuItem("Renderer/SubMesh/Split/Submeshes",
            "Split a mesh into meshes by sub-mesh. " +
            "The source is disabled and new renderers are created.",
            ContextRequirements.SubMeshes, 0)]
        public static void RendererSplit()
        {
            const string undoLabel = "Split Sub-meshes";
            var createdObjects = new List<GameObject>();
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Renderer>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                if (!SkinnEx.HasSharedMesh(context)) continue;


                var splits = new List<Renderer>();
                if (context as MeshRenderer)
                    splits = SkinnEx.MeshRendererSplit(context as MeshRenderer);
                if (context as SkinnedMeshRenderer)
                    splits = SkinnEx.SkinnedMeshSplit(context as SkinnedMeshRenderer);

                var root = new GameObject(context.gameObject.name + "_Split");
                root.transform.SetParent(context.transform, false);
                root.transform.SetParent(context.transform.parent, true);
                Undo.RegisterCreatedObjectUndo(root, undoLabel);

                foreach (var renderer in splits)
                {
                    Undo.RegisterCreatedObjectUndo(renderer, undoLabel);
                    renderer.transform.SetParent(root.transform);
                    renderer.transform.localPosition = Vector3.zero;
                    renderer.transform.localRotation = Quaternion.identity;
                    renderer.transform.localScale = Vector3.one;

                    if(renderer as SkinnedMeshRenderer)
                        SkinnContext.OptimizeMesh(renderer as SkinnedMeshRenderer);
                }

                createdObjects.Add(root);

                Undo.RecordObject(context.gameObject, undoLabel);
                context.gameObject.SetActive(false);
            }

            Selection.objects = createdObjects.ToArray();

            SkinnContext.Finished();
        }

    }
}